package com.example.everying.controller.system;


import com.example.everying.annotation.WebLog;
import com.example.everying.model.entity.system.SysConfig;
import com.example.everying.service.system.SysConfigService;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@Api(tags = "系统配置管理")
@RequestMapping("/system/config")
public class SysConfigController {

    @Autowired
    private SysConfigService sysConfigService;

    @GetMapping("/list")
    @ApiOperation(value = "查询配置列表")
    @WebLog(description = "查询配置列表")
    public Result<List<SysConfig>> listConfigs() {
        List<SysConfig> configs = sysConfigService.list();
        return Result.ok(configs);
    }

    @GetMapping("/{configKey}")
    @ApiOperation(value = "根据键名获取配置")
    @WebLog(description = "根据键名获取配置")
    public Result<String> getConfig(
            @ApiParam(name = "configKey", value = "配置键名", required = true)
            @PathVariable String configKey) {
        String configValue = sysConfigService.getConfigValue(configKey);
        return Result.ok(configValue);
    }

    @PostMapping
    @ApiOperation(value = "新增配置")
    @WebLog(description = "新增配置")
    public Result<?> addConfig(@RequestBody SysConfig sysConfig) {
        boolean saved = sysConfigService.save(sysConfig);
        return saved ? Result.ok() : Result.fail("新增配置失败");
    }

    @PutMapping
    @ApiOperation(value = "修改配置")
    @WebLog(description = "修改配置")
    public Result<?> updateConfig(@RequestBody SysConfig sysConfig) {
        boolean updated = sysConfigService.updateById(sysConfig);
        return updated ? Result.ok() : Result.fail("修改配置失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除配置")
    @WebLog(description = "删除配置")
    public Result<?> deleteConfig(
            @ApiParam(name = "id", value = "配置ID", required = true)
            @PathVariable Long id) {
        boolean removed = sysConfigService.removeById(id);
        return removed ? Result.ok() : Result.fail("删除配置失败");
    }
}
